package com.stu.jsoup.nw;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.*;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MI
 * @Date: 2021/10/3/22:54
 * @Description:
 */
public class Kzz {
    private static String url = "https://www.ninwin.cn/index.php?m=cb&show_cb_only=Y&show_listed_only=Y";

    public static void main(String[] args) throws IOException {
        Connection.Response execute = Jsoup.connect(url).method(Connection.Method.GET).ignoreContentType(true)
                .ignoreHttpErrors(true)
                .execute();
        Document rootDoc = execute.parse();
        // Element kzzListTable = rootDoc.getElementById("cb_hq");
        // Elements tbody = kzzListTable.getElementsByTag("tbody");
        // System.out.println(kzzListTable);
        NwKzzOriginal.parse(rootDoc);


    }

    public static void main1(String[] args) {
        System.out.println(StringUtils.getDigits("12.1"));
        String title = " 剩余本息：119.3，税后115.44";
        title = StringUtils.replaceEach(title.trim(), new String[]{"剩余本息：", "税后", "，"}, new String[]{"", "", "#"});
        String[] s = title.split("#");
        for (String s1 : s) {
            System.out.println(s1);
        }
        ClassPathResource classPathResource = new ClassPathResource("/");
        File file = null;
        try {
            file = classPathResource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(file.getAbsoluteFile());
    }

    @Setter
    @Getter
    @NoArgsConstructor
    @AllArgsConstructor
    @HeadRowHeight(20)
    @ColumnWidth(15)
    @ApiModel(value = "宁稳网Kzz", description = "不需要登录的那个页面")
    static class NwKzzOriginal {
        @ExcelIgnore
        @ApiModelProperty("数据时间")
        private String dataToday;

        @ExcelProperty(index = 0, value = "可转债代码")
        @ApiModelProperty("可转债代码")
        private String bondCode;

        @ExcelProperty(index = 1, value = "可转债name")
        @ApiModelProperty("可转债name")
        private String cbName;

        /**
         * <td class="cb_price2_id" title=" 剩余本息：119.3，税后115.44" style=""> 90.921</td>
         */
        @ExcelProperty(index = 2, value = "当前价格")
        @ApiModelProperty(value = "当前价格")
        private BigDecimal cbPrice;


        @ExcelProperty(index = 3, value = "剩余本息")
        @ApiModelProperty("剩余本息")
        private BigDecimal cbPrice2;

        @ApiModelProperty("剩余本息-税后")
        private BigDecimal cbPrice2Tax;

        @ApiModelProperty(value = "评级")
        private String rating;

        /**
         * class=red_t
         */
        @ExcelIgnore
        @ApiModelProperty("回售年限(年)")
        private String redT;

        /**
         * class=bond_t|可能是4年51天
         */

        @ExcelProperty(index = 4, value = "剩余年限")
        @ApiModelProperty("剩余年限")
        private BigDecimal bondT;

        @ExcelProperty(index = 5, value = "计算的收益")
        private BigDecimal calcYield;


        @ExcelProperty(index = 7, value = "转债余额")
        @ApiModelProperty("转债余额")
        private BigDecimal remainAmount;

        @ExcelIgnore
        @ApiModelProperty("余额/市值(11.0%)")
        private String cbToShare;

        /**
         * <td class="cb_BT_id BT_yield" style="background-color:#FFEBCD" title="税后收益率：7.17%">8.23%</td>
         */
        @ExcelProperty(index = 6, value = "税前收益率(%)")
        @ApiModelProperty("税前收益率(%)")
        private BigDecimal btYield;

        @ExcelIgnore
        @ApiModelProperty("税后收益率")
        private String atYield;

        /**
         * BT_red- 可能是无权
         */
        @ExcelIgnore
        @ApiModelProperty("税前回售收益")
        private String btRed;

        /**
         * 回售可能是无权
         */
        @ExcelIgnore
        @ApiModelProperty("税后回售收益")
        private String atRed;

        @ExcelIgnore
        @ApiModelProperty("纯债价值")
        private BigDecimal npvValue;

        public static List<NwKzzOriginal> parse(Document doc) {
            Element kzzListTable = doc.getElementById("cb_hq");
            Element tbody = kzzListTable.getElementsByTag("tbody").get(0);
            Elements trs = tbody.getElementsByTag("tr");
            List<NwKzzOriginal> collect = trs.stream().map(tr -> {
                String bondCode = tr.attr("data-cbcode");
                String dataToday = tr.attr("data-today");
                String cbName = tr.attr("data-cb_name");
                String rating = tr.attr("data-rating");
                Element elePrice = tr.selectFirst(".cb_price2_id");
                String cbPrice = elePrice.text().trim();

                //title=" 剩余本息：119.3，税后115.44"
                String titlepRrice = elePrice.attr("title");
                titlepRrice = StringUtils.replaceEach(titlepRrice.trim(), new String[]{"剩余本息：", "税后", "，"}, new String[]{"", "", "#"});
                String[] priceSplit = titlepRrice.split("#");

                String bondT = tr.select(".bond_t").text().trim();
                BigDecimal bondTbigDecimal;
                if (bondT.contains("天")) {
                    String[] splitYear = bondT.split("年");
                    BigDecimal divide = new BigDecimal(StringUtils.getDigits(splitYear[1])).divide(new BigDecimal("365"), 3, RoundingMode.HALF_UP);
                    bondTbigDecimal = new BigDecimal(splitYear[0]).add(divide);


                } else {
                    bondT = bondT.replace("年", "");
                    bondTbigDecimal = new BigDecimal(bondT);
                }

                String redT = tr.select(".red_t").text().trim().replace("年", "");

                String remainAmount = tr.attr("data-remain_amount");

                String cbToShare = tr.select(".cb_to_share").text();

                //税前收益率
                String btYield = tr.select(".BT_yield").text();
                //税后收益率
                String atYield = tr.select(".AT_yield").text();


                //税前回售收益
                String btRed = tr.select(".BT_red").text();
                String atRed = tr.select(".AT_red").text();


                String npvValue = tr.select(".npv_value").text().trim();

                NwKzzOriginal kzz = new NwKzzOriginal();
                kzz.setDataToday(dataToday);
                kzz.setBondCode(bondCode);
                kzz.setCbName(cbName);
                kzz.setCbPrice(new BigDecimal(cbPrice));
                kzz.setCbPrice2(new BigDecimal(priceSplit[0]));
                kzz.setCbPrice2Tax(new BigDecimal(priceSplit[1]));
                kzz.setRating(rating);
                kzz.setRedT(redT);
                kzz.setBondT(bondTbigDecimal);
                kzz.setRemainAmount(new BigDecimal(remainAmount));
                kzz.setCbToShare(cbToShare);
                kzz.setBtYield(new BigDecimal(btYield.replace("%", "")));
                kzz.setAtYield(atYield);
                kzz.setBtRed(btRed);
                kzz.setAtRed(atRed);
                kzz.setNpvValue(new BigDecimal(npvValue));
                return kzz;
            }).sorted((a, b) -> new CompareToBuilder().append(b.myYield(), a.myYield()).toComparison()).collect(Collectors.toList());
            // collect.forEach(System.out::println);
            try {
                ClassPathResource classPathResource = new ClassPathResource("/");
                File file = classPathResource.getFile();
                String fileName = file.getPath() + "/kzz_nw" + System.currentTimeMillis() + ".xlsx";
                EasyExcel.write(fileName, NwKzzOriginal.class).sheet("宁稳可转债").doWrite(collect);
                System.out.println(fileName);
            } catch (IOException e) {
            }
            return null;
        }

        public BigDecimal getCalcYield() {
            BigDecimal subtract = this.cbPrice2.subtract(this.cbPrice);
            return subtract.divide(this.bondT, 5, RoundingMode.HALF_UP);
        }

        /**
         * (剩余本息-当前价格)/剩余年限
         *
         * @return
         */
        public BigDecimal myYield() {
            return getCalcYield();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            NwKzzOriginal that = (NwKzzOriginal) o;
            return new EqualsBuilder().append(dataToday, that.dataToday).append(bondCode, that.bondCode).isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37).append(dataToday).append(bondCode).toHashCode();
        }

        @Override
        public String toString() {
            return ToStringBuilder.reflectionToString(this, ToStringStyle.NO_CLASS_NAME_STYLE);
        }
    }
}
